<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域 -->
        <el-card>
            <!-- 添加角色按钮区域 -->
            <el-row>
                <el-button type="primary" @click='addRolesBtn'>添加角色</el-button>
            </el-row>
            <!-- 角色列表区域 -->
            <el-table :data='rolesList' stripe border>
                <!-- 展开列 -->
                <el-table-column type='expand'>
                    <template slot-scope='scope'>
                        <el-row :class="['bdbottom',index1==0?'bdtop':'','vcenter']"
                            v-for='(item1,index1) in scope.row.children' :key='item1.id'>
                            <!-- 渲染一级权限 -->
                            <el-col :span='5'>
                                <el-tag closable @close='deleteRights(scope.row,item1.id)'>{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二三级权限 -->
                            <el-col :span='19'>
                                <el-row v-for='(item2,index2) in item1.children' :key='item2.id'
                                    :class='[index2 == 0?"":"bdtop","vcenter"]'>
                                    <!-- 渲染二级权限 -->
                                    <el-col :span='6'>
                                        <el-tag type='success' closable @close='deleteRights(scope.row,item2.id)'>
                                            {{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <!-- 渲染三级权限 -->
                                    <el-col :span='18'>
                                        <el-tag type='warning' v-for='(item3,index3) in item2.children' :key='item3.id'
                                            closable @close='deleteRights(scope.row,item3.id)'>
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                        <!-- <pre>
                        {{scope.row}}
                        </pre> -->
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type='index'></el-table-column>
                <el-table-column label='角色名称' prop='roleName'></el-table-column>
                <el-table-column label='角色描述' prop='roleDesc'></el-table-column>
                <el-table-column label='操作' width='300px'>
                    <template slot-scope='scope'>
                        <el-button size='mini' type="primary" icon="el-icon-edit" @click='showEditRoles(scope.row.id)'>
                            编辑
                        </el-button>
                        <el-button size='mini' type="danger" icon="el-icon-delete" @click='removeRoles(scope.row.id)'>删除
                        </el-button>
                        <el-button size='mini' type="warning" icon="el-icon-setting" @click='setRights(scope.row)'>分配权限
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 添加角色的弹框 -->
            <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close='addDialogClose'>
                <el-form :model="addRolesForm" :rules="addRolesFormRules" ref="addRolesFormRef" label-width="80px">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="addRolesForm.roleName" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="addRolesForm.roleDesc"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click='addRoles'>确 定</el-button>
                </span>
            </el-dialog>
            <!-- 修改角色的弹框 -->
            <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="50%">
                <el-form :model="editRolesForm" :rules="editRolesFormRules" ref="editRolesFormRef" label-width="80px">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="editRolesForm.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="editRolesForm.roleDesc"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editRoles">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 分配权限的弹框 -->
            <el-dialog title="分配权限" :visible.sync="rightsDialogVisible" width="50%" @close='setRightsDialog'>
                <el-tree :data="rightList" :props="rightProps" show-checkbox node-key='id' default-expand-all
                    :default-checked-keys='treeKeys' ref='rightRef'></el-tree>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="rightsDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="allotRight">确 定</el-button>
                </span>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                rolesList: [],
                // 控制添加角色弹框是否显示
                addDialogVisible: false,
                // 添加用户表单信息
                addRolesForm: {
                    roleName: '',
                    roleDesc: ''
                },
                addRolesFormRules: {
                    roleName: [
                        { required: true, message: '请输入角色名称', trigger: 'blur' },
                        { min: 2, max: 10, message: '长度在 3 到 10 个字符之间', trigger: 'blur' }
                    ]
                },
                // 控制修改角色弹框是否显示
                editDialogVisible: false,
                // 修改用户表单信息
                editRolesForm: [],
                editRolesFormRules: {
                    roleName: [
                        { required: true, message: '请输入角色名称', trigger: 'blur' },
                        { min: 2, max: 10, message: '长度在 3 到 10 个字符之间', trigger: 'blur' }
                    ]
                },
                // 控制分配权限弹框是否显示
                rightsDialogVisible: false,
                // 树形控件的数据
                rightList: [],
                // 树形控件的属性绑定对象
                rightProps: {
                    label: 'authName',
                    children: 'children'
                },
                // 设置树形控件中默认选中的内容
                treeKeys: [],
                // 保存正在操作的角色id
                rolesId: ''

            }
        },
        created() {
            this.getRolesList()
        },
        methods: {
            // 获取角色列表
            async getRolesList() {
                const { data: res } = await this.$axios.get('roles');
                if (res.meta.status !== 200) return this.$message.error('获取角色列表失败');
                this.rolesList = res.data;
                // console.log(res.data);
            },
            // 显示添加角色弹框
            addRolesBtn() {
                this.addDialogVisible = true;
            },
            // 监听添加角色弹框的关闭事件  重置表单
            addDialogClose() {
                this.$refs.addRolesFormRef.resetFields();
            },
            // 添加角色
            addRoles() {
                // 预验证
                this.$refs.addRolesFormRef.validate(async valid => {
                    if (!valid) return
                    // 发送请求
                    const { data: res } = await this.$axios.post('roles', {
                        roleName: this.addRolesForm.roleName,
                        roleDesc: this.addRolesForm.roleDesc
                    });
                    if (res.meta.status !== 201) return this.$message.error('添加角色失败');
                    this.$message.success('添加角色成功');
                    this.getRolesList();
                })
                this.addDialogVisible = false;
            },
            // 删除角色
            async removeRoles(id) {
                const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err);
                if (confirmResult !== 'confirm') return this.$message.info('已取消删除');
                // 发送请求
                const { data: res } = await this.$axios.delete('roles/' + id);
                if (res.meta.status !== 200) return this.$message.error('删除角色失败');
                this.$message.success('删除角色成功');
                this.getRolesList();
            },
            // 点击编辑按钮  获取要修改的角色信息
            async showEditRoles(id) {
                const { data: res } = await this.$axios.get('roles/' + id);
                if (res.meta.status !== 200) return this.$message.error('获取角色信息失败');
                this.editRolesForm = res.data;
                this.editDialogVisible = true;
            },
            editRoles() {
                // 预验证
                this.$refs.editRolesFormRef.validate(async valid => {
                    if (!valid) return
                    // 发送请求
                    const { data: res } = await this.$axios.put('roles/' + this.editRolesForm.roleId, {
                        roleName: this.editRolesForm.roleName,
                        roleDesc: this.editRolesForm.roleDesc
                    });
                    console.log(res);
                    if (res.meta.status !== 200) return this.$message.error('修改角色失败');
                    this.$message.success('修改角色成功');
                    this.editDialogVisible = false;
                    this.getRolesList();
                })
            },
            // 根据id 删除对应的权限
            async deleteRights(roles, rightId) {
                // 点击之后弹出确认删除的弹框
                const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err);
                if (confirmResult !== 'confirm') return this.$message.info('已取消删除');
                const { data: res } = await this.$axios.delete('roles/' + roles.id + '/rights/' + rightId);
                console.log(res);
                if (res.meta.status !== 200) return this.$message.error('删除角色权限失败');
                this.$message.success('删除角色权限成功');
                // 不建议重新获取权限列表,会重新刷新页面
                // this.getRolesList();
                roles.children = res.data;
            },
            // 分配权限
            async setRights(role) {
                this.roleId = role.id;
                // 获取树形权限列表
                const { data: res } = await this.$axios.get('rights/tree');
                if (res.meta.status !== 200) return this.$message.error('获取权限列表失败');
                this.rightList = res.data;
                // 用getLeafKeys进行递归，将三级权限添加到数组中
                this.getRights(role, this.treeKeys);

                this.rightsDialogVisible = true;
            },
            //该函数会获取到当前角色的所有三级权限 id 并添加到treeKeys中
            getRights(node, arr) {
                // 如果当前节点不包含children属性，则表示node为三级权限
                if (!node.children) {
                    return arr.push(node.id);
                };
                //递归调用
                node.children.forEach(item => {
                    return this.getRights(item, arr);
                })
            },
            // 监听分配权限弹框关闭事件，清空所有选中状态
            setRightsDialog() {
                this.treeKeys = [];
            },
            // 点击确定分配角色权限
            async allotRight() {
                //获取所有选中及半选的内容
                const keys = [
                    ...this.$refs.rightRef.getCheckedKeys(),
                    ...this.$refs.rightRef.getHalfCheckedKeys()
                ];
                const idstr = keys.join(',')
                // console.log(keys);
                const { data: res } = await this.$axios.post(`roles/${ this.roleId }/rights`, { rids: idstr });
                if (res.meta.status !== 200) return this.$message.error('分配权限失败');
                this.$message.success('分配权限成功');
                this.getRolesList();
                this.rightsDialogVisible = false;
            }
        }
    }
</script>

<style scoped>
    .el-tag {
        margin: 7px;
    }

    .bdtop {
        border-top: 1px solid #eee;
    }

    .bdbottom {
        border-bottom: solid 1px #eee;
    }

    .vcenter {
        display: flex;
        align-items: center;
    }
</style>